package org.hiucung.lib_voice.tts

import android.content.Context
import android.util.Log
import com.baidu.tts.client.SpeechError
import com.baidu.tts.client.SpeechSynthesizer
import com.baidu.tts.client.SpeechSynthesizerListener
import com.baidu.tts.client.TtsMode
import org.hiucung.lib_voice.manager.VoiceManager

/**
 * @title: VoiceTTS
 * @projectName OrangeAiVoiceApp
 * @description: TODO
 * @author Kicc
 * @date 2021/11/19 18:38
 */
object VoiceTTS : SpeechSynthesizerListener {

    /**
     * 假设我们有一个需求
     * 就是当TTS播放结束的时候执行一段操作
     */
    private val TAG = VoiceTTS::class.java.simpleName

    private var mOnTTSResultListener: OnTTSResultListener?= null

    //TTS对象
    private lateinit var mSpeechSynthesizer: SpeechSynthesizer

    //初始化TTS
    fun initTTS(mContext: Context){
        mSpeechSynthesizer = SpeechSynthesizer.getInstance()
        mSpeechSynthesizer.setContext(mContext)

        mSpeechSynthesizer.setAppId(VoiceManager.VOICE_APP_ID)
        mSpeechSynthesizer.setApiKey(VoiceManager.VOICE_APP_KEY, VoiceManager.VOICE_APP_SECRET)

        mSpeechSynthesizer.setSpeechSynthesizerListener(this)

        //其他参数
        //发声人
        setPeople(4.toString())
        //语速
        setVoiceSpeed(5.toString())
        //音量
        setVoiceVolume(5.toString())

        //初始化
        mSpeechSynthesizer.initTts(TtsMode.ONLINE)
    }

    //设置发音人
    fun setPeople(people:String){
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER,people)
    }

    //设置语速
    fun setVoiceSpeed(speed :String){
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEED,speed)
    }

    //设置音量
    fun setVoiceVolume(volume :String){
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_VOLUME,volume)
    }

    override fun onSynthesizeStart(p0: String?) {
        Log.i(TAG,"合成开始")
    }

    override fun onSynthesizeDataArrived(p0: String?, p1: ByteArray?, p2: Int, p3: Int) {

    }

    override fun onSynthesizeFinish(p0: String?) {
        Log.i(TAG,"合成结束")
    }

    override fun onSpeechStart(p0: String?) {
        Log.i(TAG,"开始播放")

    }

    override fun onSpeechProgressChanged(p0: String?, p1: Int) {

    }

    override fun onSpeechFinish(p0: String?) {
        Log.i(TAG,"播放结束")
        mOnTTSResultListener?.ttsEnd()
    }

    override fun onError(p0: String?, p1: SpeechError?) {
        Log.i(TAG, "TTS错误$p0$p1")

    }

    //播放+回调
    fun start(text: String, mOnTTSResultListener: OnTTSResultListener?){
        VoiceTTS.mOnTTSResultListener = mOnTTSResultListener
        mSpeechSynthesizer.speak(text)
    }

    //暂停
    fun pause(){
        mSpeechSynthesizer.pause()
    }

    //继续播放
    fun resume(){
        mSpeechSynthesizer.resume()
    }

    //停止播放
    fun stop(){
        mSpeechSynthesizer.stop()
    }

    //释放资源
    fun release(){
        mSpeechSynthesizer.release()
    }

    interface OnTTSResultListener{
        //播放结束
        fun ttsEnd()
    }
}